package com.hsl.hslcodemother.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hsl.hslcodemother.annotation.AuthCheck;
import com.hsl.hslcodemother.common.BaseResponse;
import com.hsl.hslcodemother.common.DeleteRequest;
import com.hsl.hslcodemother.common.ResultUtils;
import com.hsl.hslcodemother.constant.UserConstant;
import com.hsl.hslcodemother.exception.BusinessException;
import com.hsl.hslcodemother.exception.ErrorCode;
import com.hsl.hslcodemother.exception.ThrowUtils;
import com.hsl.hslcodemother.model.dto.chathistory.ChatHistoryAddRequest;
import com.hsl.hslcodemother.model.dto.chathistory.ChatHistoryQueryRequest;
import com.hsl.hslcodemother.model.dto.chathistory.ChatHistoryUpdateRequest;
import com.hsl.hslcodemother.model.entity.App;
import com.hsl.hslcodemother.model.entity.ChatHistory;
import com.hsl.hslcodemother.model.entity.User;
import com.hsl.hslcodemother.model.vo.ChatHistoryVO;
import com.hsl.hslcodemother.service.AppService;
import com.hsl.hslcodemother.service.ChatHistoryService;
import com.hsl.hslcodemother.service.UserService;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 对话历史 控制层
 *
 * @author <a href="https://gitee.com/liul3">猴赛雷</a>
 */
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

    @Resource
    private ChatHistoryService chatHistoryService;

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    /**
     * 创建对话历史
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addChatHistory(@RequestBody ChatHistoryAddRequest chatHistoryAddRequest) {
        ThrowUtils.throwIf(chatHistoryAddRequest == null, ErrorCode.PARAMS_ERROR);
        ChatHistory chatHistory = new ChatHistory();
        BeanUtil.copyProperties(chatHistoryAddRequest, chatHistory);
        boolean result = chatHistoryService.save(chatHistory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(chatHistory.getId());
    }

    /**
     * 根据 id 获取对话历史（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<ChatHistory> getChatHistoryById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        ChatHistory chatHistory = chatHistoryService.getById(id);
        ThrowUtils.throwIf(chatHistory == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(chatHistory);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<ChatHistoryVO> getChatHistoryVOById(long id) {
        BaseResponse<ChatHistory> response = getChatHistoryById(id);
        ChatHistory chatHistory = response.getData();
        return ResultUtils.success(chatHistoryService.getChatHistoryVO(chatHistory));
    }

    /**
     * 删除对话历史
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteChatHistory(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = chatHistoryService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新对话历史
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChatHistory(@RequestBody ChatHistoryUpdateRequest chatHistoryUpdateRequest) {
        if (chatHistoryUpdateRequest == null || chatHistoryUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChatHistory chatHistory = new ChatHistory();
        BeanUtil.copyProperties(chatHistoryUpdateRequest, chatHistory);
        boolean result = chatHistoryService.updateById(chatHistory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取对话历史封装列表（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChatHistoryVO>> listChatHistoryVOByPage(@RequestBody ChatHistoryQueryRequest chatHistoryQueryRequest) {
        ThrowUtils.throwIf(chatHistoryQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long pageNum = chatHistoryQueryRequest.getPageNum();
        long pageSize = chatHistoryQueryRequest.getPageSize();
        Page<ChatHistory> chatHistoryPage = chatHistoryService.page(Page.of(pageNum, pageSize),
                chatHistoryService.getQueryWrapper(chatHistoryQueryRequest));
        // 数据脱敏
        Page<ChatHistoryVO> chatHistoryVOPage = new Page<>(pageNum, pageSize, chatHistoryPage.getTotalRow());
        List<ChatHistoryVO> chatHistoryVOList = chatHistoryService.getChatHistoryVOList(chatHistoryPage.getRecords());
        chatHistoryVOPage.setRecords(chatHistoryService.fillAppAndUser(chatHistoryVOList));
        return ResultUtils.success(chatHistoryVOPage);
    }

    /**
     * 根据应用ID分页查询对话历史（应用创建者和管理员可见）
     */
    @GetMapping("/app/{appId}")
    public BaseResponse<List<ChatHistoryVO>> getChatHistoryByAppId(@PathVariable Long appId,
                                                                  @RequestParam(defaultValue = "1") Integer pageNum,
                                                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR);
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 检查应用是否存在
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查权限：只有应用创建者和管理员可以查看
        boolean isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        boolean isOwner = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR);
        
        // 查询对话历史
        List<ChatHistoryVO> chatHistoryVOList = chatHistoryService.getLatestByAppId(appId, pageNum, pageSize);
        return ResultUtils.success(chatHistoryVOList);
    }

    /**
     * 根据应用ID查询对话历史总数
     */
    @GetMapping("/app/{appId}/count")
    public BaseResponse<Long> getChatHistoryCountByAppId(@PathVariable Long appId, HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR);
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 检查应用是否存在
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查权限：只有应用创建者和管理员可以查看
        boolean isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        boolean isOwner = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR);
        
        // 查询总数
        Long count = chatHistoryService.countByAppId(appId);
        return ResultUtils.success(count);
    }

    /**
     * 保存用户消息
     */
    @PostMapping("/save/user")
    public BaseResponse<Boolean> saveUserMessage(@RequestParam Long appId,
                                                @RequestParam String content,
                                                HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(content == null || content.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 检查应用是否存在
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查权限：只有应用创建者和管理员可以保存消息
        boolean isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        boolean isOwner = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR);
        
        // 保存用户消息
        boolean result = chatHistoryService.saveUserMessage(appId, loginUser.getId(), content);
        return ResultUtils.success(result);
    }

    /**
     * 保存AI消息
     */
    @PostMapping("/save/ai")
    public BaseResponse<Boolean> saveAiMessage(@RequestParam Long appId,
                                              @RequestParam String content,
                                              HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(content == null || content.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 检查应用是否存在
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查权限：只有应用创建者和管理员可以保存消息
        boolean isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        boolean isOwner = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR);
        
        // 保存AI消息
        boolean result = chatHistoryService.saveAiMessage(appId, loginUser.getId(), content);
        return ResultUtils.success(result);
    }

    /**
     * 保存错误消息
     */
    @PostMapping("/save/error")
    public BaseResponse<Boolean> saveErrorMessage(@RequestParam Long appId,
                                                 @RequestParam String errorMessage,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(errorMessage == null || errorMessage.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 检查应用是否存在
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查权限：只有应用创建者和管理员可以保存消息
        boolean isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        boolean isOwner = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR);
        
        // 保存错误消息
        boolean result = chatHistoryService.saveErrorMessage(appId, loginUser.getId(), errorMessage);
        return ResultUtils.success(result);
    }
}